package org.common.eureka.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 跨域处理
 *
 * @author samphin
 * @since 2020-7-12 16:10:16
 */
@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //设置允许域名
        List<String> allowedOrigins = Stream.of("*").collect(Collectors.toList());
        corsConfiguration.setAllowedOrigins(allowedOrigins);
        //设置允许请求头
        List<String> allowedHeaders = Stream.of("Content-Type","X-Requested-With","accept","Origin","Access-Control-Request-Method","Access-Control-Request-Headers").collect(Collectors.toList());
        corsConfiguration.setAllowedHeaders(allowedHeaders);
        //设置允许请求方式
        List<String> allowedMethods = Stream.of("OPTIONS,POST,PUT,GET,DELETE").collect(Collectors.toList());
        corsConfiguration.setAllowedMethods(allowedMethods);
        //连接超时时间
        corsConfiguration.setMaxAge(10L);
        //大致意思是可以携带 cookie,最终的结果是可以 在跨域请求的时候获取同一个 session
        corsConfiguration.setAllowCredentials(true);
        //ExposedHeaders
        List<String> exposedHeaders = Stream.of("Access-Control-Allow-Origin","Access-Control-Allow-Credentials").collect(Collectors.toList());
        corsConfiguration.setExposedHeaders(exposedHeaders);
        /*corsConfiguration.addAllowedOrigin("*"); // 允许任何域名使用
        corsConfiguration.addAllowedHeader("*"); // 允许任何头
        corsConfiguration.addAllowedMethod("*"); // 允许任何方法（post、get等）*/
        source.registerCorsConfiguration("/**", corsConfiguration); // 对接口配置跨域设置
        return new CorsFilter(source);
    }
}
